package com.tjsinfo.tjsoa.articles.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.json.JSONArray;
import org.json.JSONObject;

import com.tjsinfo.tjsoa.articles.bo.IRulesBO;
import com.tjsinfo.tjsoa.articles.bo.ITArticlesManage;
import com.tjsinfo.tjsoa.articles.bo.IViewManage;
import com.tjsinfo.tjsoa.articles.bo.ManageSuperAction;
import com.tjsinfo.tjsoa.articles.bo.TArticlesRolesManage;
import com.tjsinfo.tjsoa.articles.bo.TArticlesUserManage;
import com.tjsinfo.tjsoa.articles.form.UpLoadActionForm;
import com.tjsinfo.tjsoa.articles.form.UploadFiles;
import com.tjsinfo.tjsoa.articles.vo.TRules;
import com.tjsinfo.tjsoa.common.DealString;
import com.tjsinfo.tjsoa.common.PaginationSupport;
import com.tjsinfo.tjsoa.common.SessionUser;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.documentationflow.xingzhengshouwen.vo.TXingzhengshouwenFujian;
import com.tjsinfo.tjsoa.system.bo.IDepartmentBo;
import com.tjsinfo.tjsoa.system.vo.Files;
import com.tjsinfo.tjsoa.system.vo.TSystemDepartment;

public class RulesAction  extends ManageSuperAction{
	private TArticlesRolesManage articlesRolesManage;
	private TArticlesUserManage articlesUserManage;
	private ITArticlesManage articlesManage;
	private IViewManage articlesViewMange;
	private IRulesBO rulesBO;
	private IDepartmentBo departmentBo;
	
	
	
	public IDepartmentBo getDepartmentBo() {
		return departmentBo;
	}
	public void setDepartmentBo(IDepartmentBo departmentBo) {
		this.departmentBo = departmentBo;
	}
	public IRulesBO getRulesBO() {
		return rulesBO;
	}
	public void setRulesBO(IRulesBO rulesBO) {
		this.rulesBO = rulesBO;
	}
	public ITArticlesManage getArticlesManage() {
		return articlesManage;
	}
	public void setArticlesManage(ITArticlesManage articlesManage) {
		this.articlesManage = articlesManage;
	}
	public TArticlesUserManage getArticlesUserManage() {
		return articlesUserManage;
	}
	public void setArticlesUserManage(TArticlesUserManage articlesUserManage) {
		this.articlesUserManage = articlesUserManage;
	}
	public TArticlesRolesManage getArticlesRolesManage() {
		return articlesRolesManage;
	}
	public void setArticlesRolesManage(TArticlesRolesManage articlesRolesManage) {
		this.articlesRolesManage = articlesRolesManage;
	}
	public IViewManage getArticlesViewMange() {
		return articlesViewMange;
	}
	public void setArticlesViewMange(IViewManage articlesViewMange) {
		this.articlesViewMange = articlesViewMange;
	}
	
	
	/**
	 * 获取管理者所有规章制度数据
	 * @return
	 */
	public ActionForward getManageRulesList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		PaginationSupport ps;
		String strstart=request.getParameter("start");  //列表分页显示当前页开始条数
 		if (strstart==null){
 			strstart="0";
 			}
 		String strlimit=request.getParameter("limit");  //列表分页显示每页显示条数
 		if (strlimit==null){
 			strlimit="20";
 			}
 		
 		
 		
		ps = rulesBO.findManageBySearch(strstart, strlimit,ToolKit.getSessionUser(request),request);
 		Integer articlelistall = ps.getTotalCount();//得到文章总数
 		List<TRules> TRulesListpage = ps.getItems();//将分页对象中获得object列表转换成Articles列表	
 		JSONArray array	 = new JSONArray();
 			for (TRules articlesL : TRulesListpage) {
 				JSONObject object = new JSONObject(articlesL);
 				object.put("createdatestr", ToolKit.FormatDate(articlesL.getCreatedate()));
 				object.put("uploaddatestr", ToolKit.FormatDate(articlesL.getUploaddate()));
 				object.put("alertdatestr", ToolKit.FormatDate(articlesL.getAlertdate()));
 				array.put(object);
 			}
	 		JSONObject jsonObject = new JSONObject();  
	 		jsonObject.put("totalCount",articlelistall);  //结果总数
	 		jsonObject.put("aricleslist", array);   //当前页文章列表
 			response.getWriter().print(jsonObject);
 			return null;
	}
	/**
	 * 获取所有规章制度数据
	 * @return
	 */
	public ActionForward getRulesList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		PaginationSupport ps;
		String strstart=request.getParameter("start");  //列表分页显示当前页开始条数
 		if (strstart==null){
 			strstart="0";
 			}
 		String strlimit=request.getParameter("limit");  //列表分页显示每页显示条数
 		if (strlimit==null){
 			strlimit="20";
 			}
		ps = rulesBO.findBySearch(strstart, strlimit,request);
 		Integer articlelistall = ps.getTotalCount();//得到文章总数
 		List<TRules> TRulesListpage = ps.getItems();//将分页对象中获得object列表转换成Articles列表	
 		JSONArray array	 = new JSONArray();
 			for (TRules articlesL : TRulesListpage) {
 				JSONObject object = new JSONObject(articlesL);
 				object.put("createdatestr", ToolKit.FormatDate(articlesL.getCreatedate()));
 				object.put("uploaddatestr", ToolKit.FormatDate(articlesL.getUploaddate()));
 				object.put("alertdatestr", ToolKit.FormatDate(articlesL.getAlertdate()));
 				array.put(object);
 			}
	 		JSONObject jsonObject = new JSONObject();  
	 		jsonObject.put("totalCount",articlelistall);  //结果总数
	 		jsonObject.put("aricleslist", array);   //当前页文章列表
 			response.getWriter().print(jsonObject);
 			return null;
	}
	
	/**
	 * 进入新建文章页面前数据处理
	 * @return
	 */
	public ActionForward toAddRules(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		String department =	SessionUser.getUser(request).getDepartment();
		TSystemDepartment systemDepartment = new TSystemDepartment();
		String[] departmentArray = department.split(",");
		for (String depId : departmentArray) {
			if(!"".equals(depId) && depId != null){
				systemDepartment = departmentBo.findById(depId);
			}
		}
		request.setAttribute("deptName", systemDepartment.getDeptName());
		
		return mapping.findForward(TOADDRules);
	}
	
	
	/**
	 * 进入修改页面前数据处理
	 * @return
	 */
	public ActionForward toUpdateRules(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		Integer id = Integer.parseInt(request.getParameter("id"));
		TRules rules = rulesBO.getRulesId(id);
		request.setAttribute("rules", rules);
		return mapping.findForward(TOUPDATERules);
	}
	
	/**
	 * 添加规章制度信息
	 * @return
	 */
	public ActionForward addRules(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		
		String toFilePath = ToolKit
				.getProperties(
						"com/tjsinfo/tjsoa/documentationflow/xingzhengshouwen/properties/systemResource.properties",
						this).getProperty("xingzhengshouwen.fileurl");
		 List<UploadFiles> fileList = new ArrayList<UploadFiles>();
		 UpLoadActionForm upLoad = (UpLoadActionForm) form;
		String title = request.getParameter("title");
		String wenhao = request.getParameter("wenhao");
		String fawenriqi = request.getParameter("fawenriqi");
		Date riqi  = ToolKit.FormatDate(fawenriqi);
		String danwei = request.getParameter("danwei");
		String bumen = request.getParameter("bumen");
		TRules rules = new TRules();
		 Map<String, FormFile> upLoadMaps = upLoad.getFilesMap();
	     if(upLoadMaps.get("file[0]") != null ){
	    	 FormFile formFile =upLoadMaps.get("file[0]");
	         UploadFiles files = uploadfile(formFile,toFilePath);
	         rules.setTitlename(files.getUploadFileName());
			 rules.setTitleurl(files.getUploadRealName());
	     }
	     if(upLoadMaps.get("file[1]") != null){
	    	 FormFile formFile =upLoadMaps.get("file[1]");
	         UploadFiles files = uploadfile(formFile,toFilePath);
	         rules.setTablename(files.getUploadFileName());
			 rules.setTableurl(files.getUploadRealName());
	     }
		rules.setTitle(title);
		rules.setWenhao(wenhao);
		rules.setCreatedate(riqi);
		rules.setDanwei(danwei);
		rules.setBumen(bumen);
		rules.setState(1);
		rules.setUploaddate(new Date());
		rules.setAlertdate(new Date());
		if(fileList.size() > 1){
			rules.setTablename(fileList.get(1).getUploadFileName());
			rules.setTableurl(fileList.get(1).getUploadRealName());
		}
		if(fileList.size() > 0){
			rules.setTitlename(fileList.get(0).getUploadFileName());
			rules.setTitleurl(fileList.get(0).getUploadRealName());

		}
		String  DepartmentId  = ToolKit.getSessionUser(request).getDepartment();
		String[]  DepartmentIdArray  = DepartmentId.split(",");
		List<String> list  = new ArrayList<String>();
		for (String id : DepartmentIdArray) {
			if(!"".equals(id) && id != null ){
				list.add(id);
			}
		}
		rules.setBumenid(Integer.parseInt(list.get(0)));
		rulesBO.addRules(rules);
		request.setAttribute("message", "save");
		return mapping.findForward(SHOWMESSAGE);
	}
	
	
	/**
	 * 添加规章制度信息
	 * @return
	 */
	public ActionForward updateRules(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		Integer id = Integer.parseInt(request.getParameter("id"));
		TRules rules = rulesBO.getRulesId(id);
		String toFilePath = ToolKit
				.getProperties(
						"com/tjsinfo/tjsoa/documentationflow/xingzhengshouwen/properties/systemResource.properties",
						this).getProperty("xingzhengshouwen.fileurl");
		 UpLoadActionForm upLoad = (UpLoadActionForm) form;
	     Map<String, FormFile> upLoadMaps = upLoad.getFilesMap();
	     if(upLoadMaps.get("file[0]") != null ){
	    	 FormFile formFile =upLoadMaps.get("file[0]");
	         UploadFiles files = uploadfile(formFile,toFilePath);
	         rules.setTitlename(files.getUploadFileName());
			 rules.setTitleurl(files.getUploadRealName());
	     }
	     if(upLoadMaps.get("file[1]") != null){
	    	 FormFile formFile =upLoadMaps.get("file[1]");
	         UploadFiles files = uploadfile(formFile,toFilePath);
	         rules.setTablename(files.getUploadFileName());
			 rules.setTableurl(files.getUploadRealName());
	     }
	    
	     
	     	String title = request.getParameter("title");
			String wenhao = request.getParameter("wenhao");
			String fawenriqi = request.getParameter("fawenriqi");
			Date riqi  = ToolKit.FormatDate(fawenriqi);
			String danwei = request.getParameter("danwei");
			String bumen = request.getParameter("bumen");
			rules.setTitle(title);
			rules.setWenhao(wenhao);
			rules.setCreatedate(riqi);
			rules.setDanwei(danwei);
			rules.setBumen(bumen);
			rules.setState(1);
			rules.setAlertdate(new Date());
			rulesBO.updateRules(rules);
			request.setAttribute("message", "update");
			return mapping.findForward(SHOWMESSAGE);
			
	}
	
	/**
	 * 添加规章制度信息
	 * @return
	 */
	public ActionForward changState(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		Integer id = Integer.parseInt(request.getParameter("id"));
		TRules rules = rulesBO.getRulesId(id);
		if (rules.getState() == 1) {
			rules.setState(0);
		}else{
			rules.setState(1);
		}
		
		rulesBO.updateRules(rules);
		JSONObject object = new JSONObject();
    	object.put("success", true);
    	response.getWriter().print(object);
    	return null;
	}
	
	/**
	 * 下载
	 * 
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward download(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		String url = "error";
		InputStream fis = null;
		OutputStream toClient = null;
		// TODO Auto-generated method stub
		try {
			Integer id = Integer.parseInt(arg2.getParameter("id"));
			TRules rules = rulesBO.getRulesId(id);
			String toFilePath = ToolKit
					.getProperties(
							"com/tjsinfo/tjsoa/documentationflow/xingzhengshouwen/properties/systemResource.properties",
							this).getProperty("xingzhengshouwen.fileurl");
			String desfile = toFilePath+rules.getTitleurl();
			File file = new File(desfile);
			String filename = rules.getTitlename();
			fis = new BufferedInputStream(new FileInputStream(desfile));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);

			arg3.reset();
			arg3.addHeader("Content-Disposition", "attachment;filename="
					+ new String(filename.getBytes(), "iso8859-1"));
			arg3.addHeader("Content-Length", "" + file.length());
			toClient = new BufferedOutputStream(arg3.getOutputStream());
			arg3.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();

			url = "ok";
		} catch (IOException ex) {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			ex.printStackTrace();
			return arg0.findForward("error");
		} catch (NullPointerException ex) {
			return null;
		} catch (Exception ex) {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return arg0.findForward("error");
		} finally {
			fis.close();
			toClient.close();
		}
		if ("ok".equals(url)) {
			return null;
		} else {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return arg0.findForward(url);
		}
	}
	
	
	/**
	 * 下载表格
	 * 
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward downloadTable(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		String url = "error";
		InputStream fis = null;
		OutputStream toClient = null;
		// TODO Auto-generated method stub
		try {
			Integer id = Integer.parseInt(arg2.getParameter("id"));
			TRules rules = rulesBO.getRulesId(id);
			String toFilePath = ToolKit
					.getProperties(
							"com/tjsinfo/tjsoa/documentationflow/xingzhengshouwen/properties/systemResource.properties",
							this).getProperty("xingzhengshouwen.fileurl");
			String desfile = toFilePath+rules.getTableurl();
			File file = new File(desfile);
			String filename = rules.getTablename();
			fis = new BufferedInputStream(new FileInputStream(desfile));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);

			arg3.reset();
			arg3.addHeader("Content-Disposition", "attachment;filename="
					+ new String(filename.getBytes(), "iso8859-1"));
			arg3.addHeader("Content-Length", "" + file.length());
			toClient = new BufferedOutputStream(arg3.getOutputStream());
			arg3.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();

			url = "ok";
		} catch (IOException ex) {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			ex.printStackTrace();
			return arg0.findForward("error");
		} catch (NullPointerException ex) {
			return null;
		} catch (Exception ex) {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return arg0.findForward("error");
		} finally {
			fis.close();
			toClient.close();
		}
		if ("ok".equals(url)) {
			return null;
		} else {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return arg0.findForward(url);
		}
	}
	
	 public UploadFiles uploadfile(FormFile file,String path) throws IOException {
	        // TODO Auto-generated method stub
	        String fileName = file.getFileName();//原文件名
	        String realName = UUID.randomUUID().toString()
	                + fileName.substring(fileName.lastIndexOf("."));//保存的文件名称，使用UUID+后缀进行保存
	        //创建文件夹，保存上传文件
	        File filepath = new File(path);
	        if (!filepath.isDirectory()) {
	            filepath.mkdir();
	        }
	        //文件上传后的路径
	        String filePath = filepath + "/" + realName;
	        
	        InputStream stream = file.getInputStream();
	        OutputStream bos = new FileOutputStream(filePath);
	        int bytesRead = 0;
	        byte[] buffer = new byte[8192];
	        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
	            bos.write(buffer, 0, bytesRead);
	        }
	        bos.close();
	        stream.close();
	        
	        //页面上显示上传的文件信息
	        UploadFiles files = new UploadFiles();
	        files.setUploadFileName(file.getFileName());
	        files.setUploadContentType(file.getContentType());
	        files.setUploadRealName(realName);
	        
	        return files;
	    }
}
